package org.kust.bbs.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.kust.bbs.admin.mapper.UserMapper;
import org.kust.bbs.admin.service.IUserService;
import org.kust.bbs.common.ex.ServiceException;
import org.kust.bbs.common.utils.MD5Utils;
import org.kust.bbs.common.web.JsonPage;
import org.kust.bbs.common.web.State;
import org.kust.bbs.pojo.dto.UserAddNewDTO;
import org.kust.bbs.pojo.entity.User;
import org.kust.bbs.pojo.vo.PageQuery;
import org.kust.bbs.pojo.vo.UserDetailsVO;
import org.kust.bbs.pojo.vo.UserSimpleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public void addNew(UserAddNewDTO userAddNewDTO) {
        //String name = userAddNewDTO.getUsername();
        String password = userAddNewDTO.getPassword();
//        UserSimpleVO queryResult = userMapper.getByUsername(name);
//        if (queryResult != null) {
//            // 是：抛出ServiceException
//            throw new ServiceException(State.ERR_NAME_DUPLICATE,
//                    "添加用户失败，名称（" + name + "）已存在！");
//        }
        User user = new User();
        BeanUtils.copyProperties(userAddNewDTO, user);
        user.setUsername(RandomStringUtils.randomAlphabetic(8) + "_" + RandomStringUtils.randomNumeric(4));
        user.setPassword(MD5Utils.MD5(password));
        user.setIsEnable(1);
        user.setGmtCreate(LocalDateTime.now());
        user.setGmtModified(LocalDateTime.now());
        int rows = userMapper.insert(user);
        // 判断返回的受影响的行数是否不为1
        if (rows != 1) {
            // 是：抛出ServiceException
            throw new ServiceException(State.ERR_INSERT,
                    "添加用户失败，服务器忙（" + State.ERR_INSERT.getValue() + "），请稍后再次尝试！");
        }
    }

    @Override
    public void updateEnableByUsername(String username) {
        UserSimpleVO queryResult = userMapper.getByUsername(username);
        if (queryResult == null) {
            // 是：抛出ServiceException
            throw new ServiceException(State.ERR_NOT_FOUND,
                    "查询用户失败，名称（" + username + "）不存在！");
        }
        int isEnable = 1;
        if (queryResult.getIsEnable() == 1) {
            isEnable = 0;
        }
        log.info("isEnable={}", queryResult.getIsEnable());
        int rows = userMapper.updateEnableByUsername(username, isEnable);
        if (rows != 1) {
            // 是：抛出ServiceException
            throw new ServiceException(State.ERR_UPDATE,
                    "更新用户失败，服务器忙（" + State.ERR_UPDATE.getValue() + "），请稍后再次尝试！");
        }
    }

    @Override
    public JsonPage<UserDetailsVO> list(PageQuery pageQuery) {
        PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getSizeNum());
        List<UserDetailsVO> list = userMapper.list();
        PageInfo pageInfo = new PageInfo(list);
        return JsonPage.restPage(pageInfo);
    }

    @Override
    public Map<String, Integer> ip() {
        Map<String, Integer> map = new HashMap<>();
        List<UserDetailsVO> list = userMapper.list();
        for (int i = 0; i < list.size(); i++) {
            String ip = list.get(i).getLastLoginIp();
            if (map.containsKey(ip)) {
                map.put(ip, map.get(ip) + 1);
            } else
                map.put(ip, 1);
        }
        return map;
    }

}
